import Cookies from 'js-cookie';
import { defineStore } from 'pinia';

const useStore = defineStore('state', {
    state: () => ({
        isCollapse: false,
        bread: null,
        tagList: [
            {
                path: '/',
                name: 'home',
                label: '首页',
                icon: 'home'
            }
        ],
        menu: [],
        token: '',
        isRoutesLoaded: false // 新增标记
    }),
    actions: {
        updateIsCollapse() {
            this.isCollapse = !this.isCollapse;
        },
        updateBreadcrumb(val) {
            if (val.name === 'home') {
                this.bread = null;
            } else {
                this.bread = val;
                const result = this.tagList.findIndex(item => item.name === val.name)
                result == -1 ? this.tagList.push(val) : '';
            }
        },
        closeTag(val) {
            const result = this.tagList.findIndex(item => item.name === val.name)
            this.tagList.splice(result, 1)
        },
        setMenu(val) {
            this.menu = val;
            localStorage.setItem('menu', JSON.stringify(val))
        },
        addMenu(router) {
            if (!localStorage.getItem('menu')) {
                return;
            }
            const menu = JSON.parse(localStorage.getItem('menu'));
            const menuArray = [];
            menu.forEach(item => {
                if (item.children) {
                    item.children = item.children.map(item => {
                        let url = `../views/${item.url}.vue`;
                        item.component = () => import(url);
                        return item;
                    });
                    menuArray.push(...item.children);
                } else {
                    let url = `../views/${item.url}.vue`;
                    item.component = () => import(url);
                    menuArray.push(item);
                }
            });
            menuArray.forEach(item => {
                router.addRoute('home1', item);
            });
        },
        clearMenu() {
            this.menu = [];
            localStorage.removeItem('menu');
        },
        setToken(val) {
            this.token = val;
            Cookies.set('token', val);
        },
        clearToken() {
            this.token = '';
            Cookies.remove('token');
        },
        getToken() {
            this.token = this.token || Cookies.get('token');
        }
    },
});

export default useStore;